package com.example.dense_rack_server.controller;


import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.dense_rack_server.entity.Archives;
import com.example.dense_rack_server.entity.BorrowingRecords;
import com.example.dense_rack_server.entity.Host;
import com.example.dense_rack_server.mapper.BorrowingRecordsMapper;
import com.example.dense_rack_server.security.dto.JwtUserDto;
import com.example.dense_rack_server.service.ArchivesService;
import com.example.dense_rack_server.service.HostService;
import com.example.dense_rack_server.utils.ResponseModel;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import java.io.IOException;
import java.text.DecimalFormat;
import java.util.*;

@Controller
public class IndexController {
    @Resource
    public ArchivesService archivesService;
    @Resource
    public HostService hostService;
    @Resource
    public BorrowingRecordsMapper borrowingRecordsMapper;

    //    public static List<String> randomColor = Arrays.asList("#D24470", "#44D9D9", "#894BDB", "#FFD88A", "#E85D2B", "#5AB8E8",
//            "#ECBC37", "#3BA1F3", "#8ADBFF", "#3355FF", "#25bd97", "#edcc31", "#b35aff", "#D24470", "#F5717E", "#BB6F2D", "#57D59A",
//            "#596BAF", "#637fea", "#CC3939"
//    );
    public static List<String> randomColor = Arrays.asList("#9E87FF", "#73DDFF", "#F56948", "#fe9a8b", "#9E87FF");

    @GetMapping("/index")
    public ModelAndView index() {
        ModelAndView modelAndView = new ModelAndView("index");
        JwtUserDto jwtUserDto = (JwtUserDto) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        String userName = jwtUserDto.getUsername();
        modelAndView.addObject("userName", userName);
        return modelAndView;
    }

    /**
     * 登录页面
     */
    @GetMapping("/login")
    public ModelAndView login() throws IOException {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("login");
        return modelAndView;
    }

    /**
     * 控制台页面
     */
    @GetMapping("/console")
    public ModelAndView console() {
        ModelAndView modelAndView = new ModelAndView("console/console1");
//        List<ArchivesArea> archivesAreaList = archivesAreaService.list();
//        ArchivesArea archivesArea = archivesAreaList.get(0);
//        List<ArchivesArea> bottomAreaList = archivesAreaMapper.bottomAreaId(archivesArea.getId());
//        ArchivesArea bottomArea = bottomAreaList.get(bottomAreaList.size() - 1);
//        modelAndView.addObject("bottomArea", bottomArea);
        List<Host> hostList = hostService.list();
        modelAndView.addObject("hostList", hostList);
        modelAndView.addObject("cabinetNumber", hostList.get(0).getCabinetNumber());
        return modelAndView;
    }

    /**
     * 数据大屏默认显示页面
     */
    @GetMapping("/console/default")
    @ResponseBody
    public ResponseModel consoleDefault() {
//        List<Integer> subordinateAreaList = archivesAreaMapper.queryAllSubordinates(Convert.toInt(hostId));
//        List<ArchivesArea> archivesAreaList = archivesAreaMapper.selectList(null);
        Map<String, Object> resultMap = new HashMap<>();
        // 库房总数
//        resultMap.put("areaCount", archivesAreaList.size());

//        QueryWrapper<Archives> archivesQueryWrapper = new QueryWrapper<>();
//        archivesQueryWrapper.in("area_code", cabinetNumber);
        List<Archives> archivesList = archivesService.list();
        // 库房总数
        resultMap.put("totalNumber", archivesList.size());
//        if (archivesList.isEmpty()) {
//            return ResponseModel.fail("此区域没有档案信息");
//        }

        int inTheLibraryCount = 0;
        int borrowingCount = 0;
        // 在库（进度条）
        int progressbarIsInTheLibrary = 0;
        // 出库（进度条）
        int progressbarIsBorrowingCount = 0;
        // 出库未取走（进度条）
        int progressbarIsOutboundNotTakenAway = 0;
        // 归还未入库（进度条）
        int progressbarIsReturnedNotYet = 0;
        for (Archives archives : archivesList) {
            if (archives.getStatus() == 0 || archives.getStatus() == 2) {
                inTheLibraryCount++;
            }
            if (archives.getStatus() == 1 || archives.getStatus() == 3) {
                borrowingCount++;
            }
            if (archives.getStatus() == 0) {
                progressbarIsInTheLibrary++;
            } else if (archives.getStatus() == 1) {
                progressbarIsBorrowingCount++;
            } else if (archives.getStatus() == 2) {
                progressbarIsOutboundNotTakenAway++;
            } else if (archives.getStatus() == 3) {
                progressbarIsReturnedNotYet++;
            }
        }
        // 在库
        resultMap.put("inTheLibraryCount", inTheLibraryCount);
        // 借出
        resultMap.put("borrowingCount", borrowingCount);
        // 进度条
        resultMap.put("progressbarIsInTheLibrary", progressbarIsInTheLibrary);
        resultMap.put("progressbarIsBorrowingCount", progressbarIsBorrowingCount);
        resultMap.put("progressbarIsOutboundNotTakenAway", progressbarIsOutboundNotTakenAway);
        resultMap.put("progressbarIsReturnedNotYet", progressbarIsReturnedNotYet);

        List<Host> hostList = hostService.list();
        int archivesCount = archivesList.size();
        List<Map<String, Object>> areaList = new ArrayList<>();
        List<Map<String, Object>> pieChartList = new ArrayList<>();
        for (Host host : hostList) {
            Map<String, Object> areaMap = new HashMap<>();
            int count = archivesService.count(new QueryWrapper<Archives>().eq("area_code", host.getCabinetNumber()));
            Double percent = (count / (double) archivesCount) * 100;
            DecimalFormat df = new DecimalFormat("#.##");
            String formattedPercentage = df.format(percent);
            areaMap.put("cabinetNumber", host.getCabinetNumber());
            areaMap.put("percent", formattedPercentage);
            areaMap.put("count", count);
            areaList.add(areaMap);

            //饼图
            Map<String, Object> pieChartMap = new HashMap<>();
            pieChartMap.put("name", host.getCabinetNumber());
            pieChartMap.put("value", count);

            if (count > 0) {
                pieChartList.add(pieChartMap);
            }
        }
        resultMap.put("areaList", areaList);
        // 饼图
        resultMap.put("pieChartList", pieChartList);
        // 柱状图
        Date nowDate = DateUtil.date();
        DateTime dateTime = DateUtil.beginOfMonth(nowDate);
        Date newDate = DateUtil.offset(dateTime, DateField.MONTH, -4);
        Map<String, Integer> lendingMap = new LinkedHashMap<String, Integer>() {
            {
                for (int i = 0; i <= 4; i++) {
                    Date offsetNewDate = DateUtil.offset(newDate, DateField.MONTH, i);
                    int year = DateUtil.year(offsetNewDate);
                    int month = DateUtil.month(offsetNewDate) + 1;
                    put(year + "-" + month + "月", 0);

                }
            }
        };
        Map<String, Integer> returnMap = new LinkedHashMap<String, Integer>() {
            {
                for (int i = 0; i <= 4; i++) {
                    Date offsetNewDate = DateUtil.offset(newDate, DateField.MONTH, i);
                    int year = DateUtil.year(offsetNewDate);
                    int month = DateUtil.month(offsetNewDate) + 1;
                    put(year + "-" + month + "月", 0);

                }
            }
        };
        Map<String, Integer> deleteMap = new LinkedHashMap<String, Integer>() {
            {
                for (int i = 0; i <= 4; i++) {
                    Date offsetNewDate = DateUtil.offset(newDate, DateField.MONTH, i);
                    int year = DateUtil.year(offsetNewDate);
                    int month = DateUtil.month(offsetNewDate) + 1;
                    put(year + "-" + month + "月", 0);

                }
            }
        };
        Map<String, Integer> insertMap = new LinkedHashMap<String, Integer>() {
            {
                for (int i = 0; i <= 4; i++) {
                    Date offsetNewDate = DateUtil.offset(newDate, DateField.MONTH, i);
                    int year = DateUtil.year(offsetNewDate);
                    int month = DateUtil.month(offsetNewDate) + 1;
                    put(year + "-" + month + "月", 0);

                }
            }
        };

        String formatDateTime = DateUtil.formatDateTime(newDate);
        QueryWrapper<BorrowingRecords> borrowingRecordsQueryWrapper = new QueryWrapper<BorrowingRecords>();
        borrowingRecordsQueryWrapper.ge("create_time", formatDateTime).eq("module_type", 2);
//        borrowingRecordsQueryWrapper.eq("area_id", cabinetNumber);
        List<BorrowingRecords> archivesRecordList = borrowingRecordsMapper.selectList(borrowingRecordsQueryWrapper);
        for (BorrowingRecords borrowingRecords : archivesRecordList) {
            Date date = DateUtil.parse(borrowingRecords.getCreateTime(), "yyyy-MM-dd");
            int year = DateUtil.year(date);
            int month = DateUtil.month(date) + 1;
            if (borrowingRecords.getDataStatus() == 1 || borrowingRecords.getDataStatus() == 3) {
                int count = lendingMap.get(year + "-" + month + "月") + 1;
                returnMap.put(year + "-" + month + "月", count);
            }
            if (borrowingRecords.getDataStatus() == 0 || borrowingRecords.getDataStatus() == 2) {
                int count = returnMap.get(year + "-" + month + "月") + 1;
                lendingMap.put(year + "-" + month + "月", count);
            }
            if (borrowingRecords.getDataStatus() == 4) {
                int count = deleteMap.get(year + "-" + month + "月") + 1;
                deleteMap.put(year + "-" + month + "月", count);
            }
            if (borrowingRecords.getDataStatus() == 5) {
                int count = insertMap.get(year + "-" + month + "月") + 1;
                insertMap.put(year + "-" + month + "月", count);
            }
        }
        List<Object> xName = new ArrayList<>(lendingMap.keySet());
        resultMap.put("barChartXName", xName);
        List<Object> lendingList = new ArrayList<>(lendingMap.values());
        resultMap.put("barChartLendingList", lendingList);
        List<Object> returnList = new ArrayList<>(returnMap.values());
        resultMap.put("barChartReturnList", returnList);
        List<Object> deleteStrList = new ArrayList<>(deleteMap.values());
        resultMap.put("deleteStrList", deleteStrList);
        List<Object> insertList = new ArrayList<>(insertMap.values());
        resultMap.put("insertList", insertList);
        return ResponseModel.success(resultMap);

//        //在库数
//        QueryWrapper<Archives> inTheLibraryQuery = new QueryWrapper<>();
//        inTheLibraryQuery.in("archives_area_id",subordinateAreaList).and(i->i.eq("status", 0).or().eq("status", 2));
//        int inTheLibraryCount = archivesService.count(inTheLibraryQuery);
//        result.put("inTheLibraryCount", inTheLibraryCount);
//        //借出数
//        QueryWrapper<Archives> borrowingQuery = new QueryWrapper<>();
//        borrowingQuery.in("archives_area_id",subordinateAreaList).and(i->i.eq("status", 1).or().eq("status", 3));
//        int borrowingCount = archivesService.count(borrowingQuery);
//        result.put("borrowingCount", borrowingCount);

    }

    @GetMapping("/console/cabinet/info")
    public ModelAndView hostInfo(@RequestParam(value = "hostId") String hostId,
                                 @RequestParam(value = "column") String column) {
        Host host = hostService.getById(hostId);
        int areaCode = host.getCabinetNumber();
        QueryWrapper<Archives> archivesQueryWrapper = new QueryWrapper<Archives>().eq("area_code", areaCode).eq("column_number", column);
        List<Archives> archivesList = archivesService.list(archivesQueryWrapper);
        int allCount = archivesList.size();
        int borrowCount = 0;
        int inTheLibraryCount = 0;
        Date nowDate = DateUtil.date();
        int nowMonth = nowDate.getMonth() + 1;
        int nowMonthCount = 0;//本月新增档案数量
        for (Archives archives : archivesList) {
            if (archives.getStatus() == 1 || archives.getStatus() == 3) {
                borrowCount++;
            }
            if (archives.getStatus() == 0 || archives.getStatus() == 2) {
                inTheLibraryCount++;
            }

            //本月新增档案数量
            Date date = DateUtil.parse(archives.getCreateTime());
            int month = date.getMonth() + 1;
            if (month == nowMonth) {
                nowMonthCount++;
            }
        }

        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("allCount", allCount);
        modelAndView.addObject("borrowCount", borrowCount);
        modelAndView.addObject("inTheLibraryCount", inTheLibraryCount);
        modelAndView.addObject("nowMonthCount", nowMonthCount);
        modelAndView.setViewName("console/hostInfo");

        Date date = DateUtil.date();
        DateTime beginOfMonth =DateUtil.beginOfMonth(date);
        DateTime endOfMonth =DateUtil.endOfMonth(date);
        QueryWrapper<BorrowingRecords> borrowingRecordsQueryWrapper =new QueryWrapper<BorrowingRecords>()
                .eq("module_type",2).in("data_status",Arrays.asList(0,1,2,3));
        borrowingRecordsQueryWrapper.ge("create_time",beginOfMonth);
        borrowingRecordsQueryWrapper.le("create_time",endOfMonth);
        List<BorrowingRecords> borrowingRecordsList = borrowingRecordsMapper.selectList(borrowingRecordsQueryWrapper);
        int loanQuantity = 0;
        int returnQuantity = 0;
        for (BorrowingRecords borrowingRecords : borrowingRecordsList) {
            if (borrowingRecords.getDataStatus() == 1 || borrowingRecords.getDataStatus() == 3) {
                returnQuantity++;
            }else if (borrowingRecords.getDataStatus() == 0 || borrowingRecords.getDataStatus() == 2) {
                loanQuantity++;
            }
        }
        modelAndView.addObject("loanQuantity", loanQuantity);
        modelAndView.addObject("returnQuantity", returnQuantity);
        return modelAndView;

    }

    /**
     * 数据大屏信息
     *
     * @return
     */
    @GetMapping("/console/data")
    @ResponseBody
    public Map<String, Object> consoleData(@RequestParam(value = "areaId", required = false) String areaId) {
        Map<String, Object> result = new HashMap<>();


//        List<ArchivesArea> areaList = archivesAreaService.list();
//        if (!areaList.isEmpty()) {
//            modelAndView.addObject("areaList", areaList);
//        }
        return result;
    }


    /**
     * 三维饼图测试页面
     * @return
     */
    @GetMapping("/test")
    public String test() {
        return "test1/test";
    }

}
